import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class DeleteNonJavaFiles {

    public static void main(String[] args) {
        String currentDirectory = System.getProperty("user.dir"); // 获取当前路径
        File directory = new File(currentDirectory);

        if (!directory.exists() || !directory.isDirectory()) {
            System.err.println("当前路径不存在或不是一个目录。");
            return;
        }

        File[] files = directory.listFiles();

        if (files != null) {
            for (File file : files) {
                if (!file.getName().endsWith(".java") && !file.getName().endsWith(".txt")) {
                    deleteFileOrDirectory(file.toPath());
                }
            }
        }
    }

    private static void deleteFileOrDirectory(Path path) {
        try {
            if (Files.isDirectory(path)) {
                Files.walk(path)
                        .sorted(java.util.Comparator.reverseOrder())
                        .forEach(DeleteNonJavaFiles::deleteFile);
            } else {
                deleteFile(path);
            }
        } catch (IOException e) {
            System.err.println("删除 " + path + " 时出错：" + e.getMessage());
        }
    }

    private static void deleteFile(Path path) {
        try {
            Files.delete(path);
            System.out.println("已删除: " + path);
        } catch (IOException e) {
            System.err.println("删除 " + path + " 时出错：" + e.getMessage());
        }
    }
}
